package TOP101;

import java.util.Stack;

/**
 * @Question BM11
 * @Date 2022/11/3 21:03
 * @Solution
 */
public class BM11 {
    //辅助栈
    public ListNode addInList(ListNode head1, ListNode head2) {
        Stack<ListNode> stack1 = new Stack<>();
        Stack<ListNode> stack2 = new Stack<>();
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        while (cur1 != null) {
            stack1.push(cur1);
            cur1 = cur1.next;
        }
        while (cur2 != null) {
            stack2.push(cur2);
            cur2 = cur2.next;
        }
        ListNode head = null;
        int flag = 0;
        while (!stack1.isEmpty() && !stack2.isEmpty()) {
            cur1 = stack1.pop();
            cur2 = stack2.pop();
            ListNode node = new ListNode((cur1.val + cur2.val + flag) % 10);
            flag = (cur1.val + cur2.val + flag) / 10;
            node.next = head;
            head = node;
        }
        while (!stack1.isEmpty()) {
            cur1 = stack1.pop();
            ListNode node = new ListNode((cur1.val + flag) % 10);
            flag = (cur1.val + flag) / 10;
            node.next = head;
            head = node;
        }
        while (!stack2.isEmpty()) {
            cur2 = stack2.pop();
            ListNode node = new ListNode((cur2.val + flag) % 10);
            flag = (cur2.val + flag) / 10;
            node.next = head;
            head = node;
        }
        if (flag == 1) {
            ListNode node = new ListNode(1);
            node.next = head;
            head = node;
        }
        return head;
    }
}
